<template>
   <div class="list">
      <!-- 顶部搜索 -->
      <div class="search">
         <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="关键字">
               <el-input v-model="formInline.keyword" placeholder="请输入关键字"></el-input>
            </el-form-item>
            <el-form-item>
               <el-button type="primary" @click="__getOrdersList">查询</el-button>
            </el-form-item>
         </el-form>
      </div>
      <!-- 顶部按钮 -->
      <div class="option">
         <el-button type="warning" plain @click="__exportExl">导出</el-button>
      </div>
      <!-- 表格数据 -->
      <el-table ref="multipleTable" border :data="tableData" tooltip-effect="dark" style="width: 100%" height="452">
         <el-table-column label="编号" width="55" type="index" :index="indexMethod">
         </el-table-column>
         <el-table-column label="用户名">
            <template slot-scope="{row}">{{ row.username }}</template>
         </el-table-column>
         <el-table-column label="头像" width="80">
            <template slot-scope="{row}">
               <div style="display: flex; justify-content: center; border-radius: 50%;">
                  <img style="width: 46px;" :src="row.avatar" alt="">
               </div>
            </template>
         </el-table-column>
         <el-table-column label="订单编号" width="280">
            <template slot-scope="{row}">
               {{ truncateString(row.outTradeNo) }}
            </template>
         </el-table-column>
         <el-table-column label="商品总价">
            <template slot-scope="{row}">
               ￥{{ row.totalAmount }}
            </template>
         </el-table-column>
         <el-table-column label="订单状态">
            <template slot-scope="{row}" v-if="row">{{ orderState[row.orderStatus] }}</template>
         </el-table-column>
         <!-- 确认发货 -->
         <el-table-column label="确认发货" width="280">
            <template slot-scope="{row}">
               <el-button type="success" round @click="shipments(row)">确认发货</el-button>
            </template>
         </el-table-column>
         <!-- 操作按钮 -->
         <el-table-column label="操作" width="80" row-style="{color: '#1890ff'}">
            <template slot-scope="{row}">
               <span style="color: #409eff; margin-right: 6px; cursor: pointer;" @click="dialogFormVisible = true">
                  <i class="el-icon-view" style="margin-right: 4px;"></i><span @click="orderInfo(row)">查看</span>
               </span>
            </template>
         </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination">
         <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
            :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="total">
         </el-pagination>
      </div>
      <!-- 查看订单详情 -->
      <el-drawer
         title="订单详情"
         :visible.sync="openOrdersDetail"
         direction="rtl"
         size="60%"
         :before-close="handleClose"
         v-if="!!rowData"
      >
         <el-descriptions class="margin-top" :column="3" size="small" border style="padding: 10px !important;">
            <el-descriptions-item>
               <template slot="label">
               <i class="el-icon-user"></i>
               收货人
               </template>
               {{ rowData.receiverInfo.split(' ')[0] }}
            </el-descriptions-item>
            <el-descriptions-item>
               <template slot="label">
               <i class="el-icon-mobile-phone"></i>
               手机号
               </template>
               {{ rowData.receiverInfo.split(' ')[1] }}
            </el-descriptions-item>
            <el-descriptions-item>
               <template slot="label">
               <i class="el-icon-location-outline"></i>
               实付总价
               </template>
               {{ rowData.totalAmount }}
            </el-descriptions-item>
            <el-descriptions-item>
               <template slot="label">
               <i class="el-icon-tickets"></i>
               支付方式
               </template>
               支付宝
            </el-descriptions-item>
            <el-descriptions-item>
               <template slot="label">
               <i class="el-icon-tickets"></i>
               商家订单号
               </template>
               {{ rowData.tradeNo }}
            </el-descriptions-item>
            <el-descriptions-item>
               <template slot="label">
               <i class="el-icon-tickets"></i>
               支付宝订单号
               </template>
               {{ rowData.outTradeNo }}
            </el-descriptions-item>
            <el-descriptions-item :span="3">
               <template slot="label">
               <i class="el-icon-tickets"></i>
               收货地址
               </template>
               {{ rowData.addressFull }}
            </el-descriptions-item>
         </el-descriptions>
         
         <div class="oo">
            <h2>购买的商品</h2>
            <div class="product" v-for="(item, index) in orderDetail" :key="index">
               <img :src="item.coverUrl" class="image">
               <div class="right">
                  <span>{{ item.name }}</span>
                  <div class="info">
                     <div style="margin-bottom: 5px;"><strong>购买数量：</strong>{{ item.productNum }}</div>
                     <div style="margin-bottom: 5px;"><strong>实付金额：</strong>￥{{ item.totalAmount }}</div>
                     <div><strong>商品规格：</strong>{{ item.productSpec }}</div>
                  </div>
               </div>
            </div>
         </div>
      </el-drawer>
   </div>
</template>

<script>
import { getOrdersListApi, getOrdersDetailApi, shipmentsApi } from "@/api/orders"
import { saveAs } from 'file-saver'

export default {
   name: "",
   data() {
      return {
         formInline: {
            keyword: '',
            orderStatus: null
         },
         orderDetail: null,
         rowData: null,
         currentDate: new Date(),
         openOrdersDetail: false,
         dialogFormVisible: false,
         formLabelWidth: '120px',
         tableData: null,
         multipleSelection: [], // 复选框的值
         pageNum: 1,
         pageSize: 10,
         total: 0,
         orderState: ['', '待付款', '待发货', '待收货', '已完成']
      }
   },
   created() {
      this.__getOrdersList()
   },
   methods: {
      async __getOrdersList() {
         let data = {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            keyword: this.formInline.keyword,
            orderStatus: 2
         }
         const res = await getOrdersListApi(data);
         // console.log("list: "+ res);
         if (!res) return;
         this.tableData = res.data.rows
         this.total = res.data.total
         // console.log("订单列表", this.tableData);
      },
      async __exportExl() {
         // const res = await exportProductApi();
         let res = null;
         if (!res) return;
         // 处理成表格文件之后调用一个保存数据的方法，浏览器会自动下载
         // console.log(res);
         saveAs(
            // Blob 对象表格一个不可变、原始数据的类文件对象
            // Blob 表示的不一定是JavaScript原生格式的数据
            // File 接口基于Blob，继承了blob的功能并将其扩展使其支持用户系统上的文件
            // 返回一个新创建的Blob对象，其内容参数中给定的数组串联组成
            new Blob([res]),
            // 设置导出文件名称
            `订单列表_${new Date().getTime()}.xlsx`
         )
      },
      async __getOrdersDetail(id) {
         const res = await getOrdersDetailApi({ orderId: id });
         if (!res) return;
         this.orderDetail = res.data;
      },
      async shipments(row) {
         const res = await shipmentsApi({ orderId: row.id });
         if (!res) return;
         this.$message({message: '发货成功', type: 'success'});
         this.__getOrdersList()
      },
      orderInfo(row) {
         // console.log(row);
         this.rowData = row
         this.__getOrdersDetail(row.id)
         this.openOrdersDetail = true
         
      },
      handleClose() {
         this.openOrdersDetail = false
      },
      indexMethod(index) {
         // 计算编号
         return (this.pageNum - 1) * this.pageSize + index + 1;
      },
      truncateString(str, length = 26) {
         // 如果字符串长度小于或等于长度限制，直接返回原字符串
         if (str.length <= length) {
            return str;
         }
         // 截取指定长度的字符串，并在末尾添加省略号
         const truncated = str.slice(0, length - 3) + '...';
         return truncated;
      },
      toggleSelection(rows) {
         console.log("rows: " + rows);
         if (rows) {
            rows.forEach(row => {
               this.$refs.multipleTable.toggleRowSelection(row);
            });
         } else {
            this.$refs.multipleTable.clearSelection();
         }
      },
      handleSelectionChange(val) { // 每点击一次复选框 发生的事件
         this.multipleSelection = val;
         console.log("multipleSelection: ", this.multipleSelection);
      },
      handleSizeChange(val) {
         this.pageSize = val
         this.__getProductList()
         console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
         this.pageNum = val
         this.__getProductList()
         console.log(`当前页: ${val}`);
      }
   }
}
</script>

<style lang="less" scoped>
.option {
   margin: -4px 0 10px 0;
}

.pagination {
   display: flex;
   justify-content: flex-end;
   padding: 8px 40px;
}

.list {
   box-sizing: border-box;
}

.el-button {
   padding: 8px 10px !important;
}

.el-input__inner {
   height: 34px !important;
}

.oo {
   padding: 15px;
   font-family: Arial, sans-serif;
   // background-color: #f9f9f9;
   border-radius: 8px;
   // box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);

   h2 {
      margin-bottom: 15px;
      font-size: 18px;
      color: #333;
   }

   .product {
      display: flex;
      border: 1px solid #ddd;
      background-color: #f9f9f9;
      margin-bottom: 6px;
      border-radius: 8px; overflow: hidden;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);

      img {
         display: block;
         width: 150px;
         height: auto;
         border-right: 1px solid #ddd;
      }

      .right {
         margin-left: 20px;
         padding: 10px;
         flex: 1;

         span {
            display: block;
            font-size: 16px;
            font-weight: bold;
            color: #333;
         }

         .info {
            margin-top: 10px;
            color: #666;
            font-size: 14px;

         }
      }
   }
}
</style>
